<template>
    <TheElDialog :title="title" :visible.sync="centerDialogVisible" @close="handleCenterDialogClose" v-bind="$attrs">
        <el-form
            @submit.native.prevent
            ref="formRule"
            :model="form"
            :rules="rules"
            :label-width="isMobile ? '80px' : '120px'"
        >
            <el-form-item prop="name" label="用户名">
                <el-input :disabled="form.isRoot" v-model="form.name" placeholder="请填写用户名"></el-input>
            </el-form-item>
            <el-form-item prop="email" label="邮箱">
                <el-input :disabled="isRootEdit" v-model="form.email" placeholder="请填写邮箱"></el-input>
            </el-form-item>
            <el-form-item prop="password" label="密码">
                <el-input :disabled="isRootEdit" v-model="form.password" placeholder="请填写密码"></el-input>
            </el-form-item>
            <el-form-item prop="password2" label="确认密码">
                <el-input :disabled="isRootEdit" v-model="form.password2" placeholder="请填写密码"></el-input>
            </el-form-item>
            <el-form-item prop="roleId" label="角色">
                <el-select
                    v-model="form.roleId"
                    placeholder="请选择角色"
                    @change="handleSelectedRoleChange"
                    multiple
                    clearable
                    :disabled="form.isRoot"
                    style="width: 100%"
                >
                    <template v-for="item in optionsRolesInput">
                        <el-option :label="item.label" :value="item.value" :key="item.value"></el-option>
                    </template>
                </el-select>
            </el-form-item>
            <el-form-item prop="permission" label="权限">
                <PermissionCheckboxGroup
                    :is-detail="true"
                    :model-permission="modelPermission"
                    @change="handlePerimissionChange"
                    v-model="form.permission"
                    form-label-width="0px"
                />
            </el-form-item>
            <el-form-item prop="remark" label="备注">
                <el-input
                    :disabled="form.isRoot"
                    type="textarea"
                    v-model="form.remark"
                    placeholder="请填写用户备注"
                ></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button :disabled="centerDialogLoading" @click="centerDialogVisible = false">取 消</el-button>
            <el-button
                :disabled="isRootEdit"
                :loading="centerDialogLoading"
                type="primary"
                @click="handleSubmit('formRule')"
                >确 定</el-button
            >
        </span>
    </TheElDialog>
</template>
<script>
import moment from 'moment';
import {putBillList, postBillList} from '@/api/bill';
import {deepCopy} from '@/utils/utils';
import {BASIC_MONEY} from '@/utils/constant';
import {colorSuccess, colorDanger} from '@/styles/variables.scss';
import PermissionCheckboxGroup from '@/components/PermissionCheckboxGroup/index.vue';
import {getRolesByIdPermission} from '@/api/role';
import {postUsers, putUsers} from '@/api/auth';
import {mapGetters} from 'vuex';
export default {
    name: 'user-dialog',
    props: {
        title: {
            type: String,
            default: '用户'
        },
        visible: {
            type: Boolean,
            default: false
        },
        optionsRoles: {
            type: Array,
            default: () => []
        },
        dataSource: {
            type: Object,
            default: () => ({
                id: undefined, // 用户id
                isRoot: false, // 是否为平台管理员
                roleId: [], // 角色id
                name: '', // 用户名
                email: '', // 邮箱
                password: '', // 密码
                password2: '', // 确认密码
                remark: '', // 备注
                modelPermission: {
                    childModules: [],
                    functionMap: {},
                    parentModules: [],
                    selectedFunctions: [],
                    selectedModules: []
                } // 权限
            })
        }
    },
    components: {
        PermissionCheckboxGroup
    },
    data() {
        const validatePermission = (rule, value, callback) => {
            const newVal = value || [];
            const length = newVal.length;
            if (length === 0) {
                return callback(new Error('权限为空'));
            }
            callback();
        };
        const validateRoleIds = (rule, value, callback) => {
            const newVal = value || [];
            const length = newVal.length;
            if (length === 0) {
                return callback(new Error('请选择角色'));
            }
            callback();
        };

        return {
            moment,
            // 新建用户弹窗 提交表单中
            centerDialogLoading: false,
            inputStyle: {width: '320px'},
            modelPermission: {
                childModules: [],
                functionMap: {},
                parentModules: [],
                selectedFunctions: [],
                selectedModules: []
            }, // 权限数据
            // 新建用户表单
            form: {
                id: undefined, // 用户id
                isRoot: false, // 是否为平台管理员
                name: '', // 用户名
                email: '', // 邮箱
                password: '', // 密码
                password2: '', // 确认密码
                remark: '', // 备注
                roleId: [], // 角色ids
                permission: []
            },
            rules: {
                name: [{required: true, message: '请填写用户名', trigger: ['change', 'blur']}],
                email: [
                    // {required: true, message: '请填写邮箱', trigger: ['change', 'blur']},
                    {type: 'email', message: '邮箱格式不正确', trigger: ['change', 'blur']}
                ],
                password: [{required: true, message: '请填写密码', trigger: ['change', 'blur']}],
                password2: [{required: true, message: '请填写确认密码', trigger: ['change', 'blur']}],
                roleId: [
                    {required: true, message: '请选择角色', trigger: ['change', 'blur']},
                    {validator: validateRoleIds, trigger: ['change', 'blur']}
                ],
                permission: [
                    {required: true, message: '请填写权限', trigger: ['change', 'blur']},
                    {validator: validatePermission, trigger: ['change', 'blur']}
                ]
                // remark: [{required: false, message: '请填写用户备注', trigger: ['change', 'blur']}]
            }
        };
    },
    computed: {
        ...mapGetters({
            user: 'user/user'
        }),
        isMobile() {
            return this.$store.getters['app/isMobile'];
        },
        // 是否为当前管理员编辑
        isRootEdit() {
            if (this.user.name === this.form.name) {
                // 即自己就是管理员
                // 平台管理员可以修改自己，其他人不可以
                return false;
            }
            return this.form.isRoot;
        },
        centerDialogVisible: {
            get() {
                return this.visible;
            },
            set(val) {
                this.$emit('update:visible', val);
            }
        },
        optionsRolesInput() {
            return this.optionsRoles;
        }
    },
    watch: {
        dataSource: {
            handler(val) {
                const modelPermission = val.modelPermission || {};
                const {_id, name, roles, email, password, password2, remark, isRoot} = val;

                this.form = {
                    _id, // 用户id
                    isRoot, // 是否为平台管理员
                    name, // 用户名
                    email, // 邮箱
                    password, // 密码
                    password2, // 确认密码
                    remark, // 备注
                    roleId: (roles || []).map(i => i.id), // 角色ids
                    permission: []
                };

                this.modelPermission = deepCopy(modelPermission);
            },
            deep: true,
            immediate: true
        }
    },
    methods: {
        // 自定义校验permissions_ids
        handlePerimissionChange() {
            this.$refs['formRule'].validateField('permission');
        },
        // 选中角色改变
        async handleSelectedRoleChange(value) {
            // 多个角色id 用逗号隔开
            const roleId = (value || []).join(',');
            if (!roleId) {
                this.modelPermission = {...this.modelPermission, selectedFunctions: [], selectedModules: []};
                // 角色id为空
                return;
            }
            try {
                const {
                    data: {data, status}
                } = await getRolesByIdPermission(roleId);
                if (status === 200) {
                    console.log('data :', data);
                    this.modelPermission = data;
                }
            } catch (error) {}
        },
        // 提交用户
        handleSubmit(formName) {
            this.$refs[formName].validate((valid, fields) => {
                const {_id, name, email, roleId, password, password2, remark} = this.form;
                if (valid) {
                    const newUser = {
                        _id, // 用户id
                        name, // 用户名
                        email, // 邮箱
                        password, // 密码
                        password2, // 确认密码
                        remark: remark || '', // 备注
                        roles: roleId.join(',') // 角色ids
                    };
                    if (this.title === '添加用户') {
                        this.handleCreate(newUser);
                    }
                    if (this.title === '编辑用户') {
                        this.handlePut(newUser);
                    }
                } else {
                    const first = Object.keys(fields)[0];
                    const items = fields[first] || [];
                    const {message} = items[0] || {};
                    this.$message({showClose: true, type: 'error', message});
                    return false;
                }
            });
        },
        // 创建用户
        handleCreate(newUser) {
            this.centerDialogLoading = true;
            postUsers(newUser)
                .then(({data: res}) => {
                    if (res.status === 201) {
                        this.$message({showClose: true, type: 'success', message: '创建用户成功'});
                        this.centerDialogVisible = false;
                        // this.getList();
                        // 重新更新数据
                        this.$emit('on-ok');
                    } else {
                        throw new Error(res);
                    }
                })
                .finally(() => {
                    this.centerDialogLoading = false;
                });
        },
        // 更新
        handlePut(newUser) {
            this.centerDialogLoading = true;
            putUsers(newUser._id, newUser)
                .then(({data: res}) => {
                    if (res.status === 204) {
                        this.$message({showClose: true, type: 'success', message: '更新用户成功'});
                        this.centerDialogVisible = false;
                        // this.getList();
                        // 重新更新数据
                        this.$emit('on-ok');
                    } else {
                        throw new Error(res);
                    }
                })
                .catch(error => {
                    this.$message({showClose: true, type: 'error', message: error});
                })
                .finally(() => {
                    this.centerDialogLoading = false;
                });
        },
        // 编辑单个用户
        handleEditItem(stages, index) {
            // item.isEdit = !item.isEdit;
            const newStages = deepCopy(stages);
            newStages[index].isEdit = !newStages[index].isEdit;

            this.form = {...this.form, stages: newStages};

            this.isEditAll = this.handleIsEditAll(newStages);
            // const isEditY = newStages.map(y => {
            //     return y.isEdit;
            // });

            // this.isEditAll = !isEditY.every(i => i === false);
        },
        // dialog 关闭
        handleCenterDialogClose() {
            // 关闭
            this.$emit('close');

            this.form = {
                _id: undefined, // 用户id
                name: '', // 用户名
                email: '', // 邮箱
                password: '', // 密码
                password2: '', // 确认密码
                remark: '', // 备注
                roleId: [], // 角色ids
                permission: []
            };
            this.modelPermission = {
                childModules: [],
                functionMap: {},
                parentModules: [],
                selectedFunctions: [],
                selectedModules: []
            }; // 权限数据
        }
    }
};
</script>
